package com.shuqi.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebViewDatabase;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.WebkitUrlDealer;
import com.shuqi.common.utils.JsonUtils;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.interfaces.web.ShuqiWebJsBaseInterface;
import com.shuqi.model.ShareModel;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

public class WebCommonActivity extends ActivityBase implements OnClickListener{
    private final String logTag = "WebCommonActivity";
    
    /**intent参数名:String 页面标题*/
    public static final String INTENT_EXTRANAME_TITLE = "pageTitle";
    /**intent参数名:String 要打开的页面url*/
    public static final String INTENT_EXTRANAME_URL = "targetUrl";
    
    private WebView webView;
    private View netErrorView;
    private View loadingView;
    private CommonTitle titleView;
    
    private String currentUrl;

    protected WebkitUrlDealer urlDealer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_webcommon);
        if (Util.isWebViewProbablyCorrupt(this)) {
            ActivityManager.getInstance().finishActivity(this);
        }
        if (WebViewDatabase.getInstance(this) == null) {
            WebView oww = new WebView(this);
            oww.clearCache(true);
            ActivityManager.getInstance().finishActivity(this);
        }
        urlDealer = new WebkitUrlDealer(this);
        findViews();
        getIntentData();
        initPage();
    }
    
    private String getIntentData(){
        Intent intent = getIntent();
        if(intent!=null){
            String titleName = intent.getStringExtra(INTENT_EXTRANAME_TITLE);
            currentUrl = urlDealer.dealUrl(intent.getStringExtra(INTENT_EXTRANAME_URL));
            setTitleName(titleName);
        }
        if("open".equals(intent.getStringExtra("push_action"))){
            StatisticsUtils.onEvent(this,StatisticsEventID.PUSHMESSAGE_ACTION_OPEN);
        }
        return "";
    }
    
    private void findViews(){
        webView = (WebView) findViewById(R.id.webcommon_webview);
        netErrorView = findViewById(R.id.include_error);
        loadingView = findViewById(R.id.include_loading);
        titleView = (CommonTitle) findViewById(R.id.title);
        titleView.setLeftClickListener(this);
        findViewById(R.id.retry).setOnClickListener(this);
    }
    private void setTitleName(String title){
        if(!TextUtils.isEmpty(title)){
            titleView.setTitle(title);
        }
    }
    
    private void onLoadingStart(){
        loadingView.setVisibility(View.VISIBLE);
    }
    private void onLoadingError(){
        netErrorView.setVisibility(View.VISIBLE);
        loadingView.setVisibility(View.GONE);
        webView.setVisibility(View.GONE);
    }
    private void onLoadingFinish(){
        loadingView.setVisibility(View.GONE);
    }
    
    /**重试*/
    private void doRetry() {
        NetErrorProvider.getInstance().retry(this, new NetErrorListener() {
            @Override
            public void netErrorCallback() {
                if (webView != null && !TextUtils.isEmpty(currentUrl)) {
                    webView.stopLoading();
                    webView.clearView();
                    netErrorView.setVisibility(View.GONE);
                    webView.setVisibility(View.VISIBLE);
                    webView.loadUrl(currentUrl);
                }
            }
        });
    }
    
    private void initPage() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new ShuqiWebJavaScript(), ShuqiWebJsBaseInterface.JS_OBJECT);
        // 缩放功能
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log4an.d(logTag, "shouldOverrideUrlLoading() url = " + url);
                if (!TextUtils.isEmpty(url) && url.startsWith("http")) {
                    view.loadUrl(urlDealer.dealUrl(new StringBuilder(50).append(url)));
                }else{
                    Log4an.e(logTag, "shouldOverrideUrlLoading() url = " + url);
                }
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log4an.i(logTag, "onPageStarted ");
                currentUrl = url;
                onLoadingStart();
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log4an.i(logTag, "onPageFinished");
                onLoadingFinish();
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                    String failingUrl) {
                Log4an.e(logTag, "onReceivedError:" + errorCode + ", " + description);
                onLoadingError();
            }
        });
        webView.setWebChromeClient(new WebChromeClient());
        onLoadingStart();
        webView.loadUrl(currentUrl);
    }

    @Override
    public void activityLogicForward() {}

    @Override
    public void activityInitData() {}
    
    public class ShuqiWebJavaScript extends ShuqiWebJsBaseInterface{

        @Override
        public void refresh() {
            if(webView!=null && webView.isShown()){
                webView.reload();
            }
        }

        @Override
        public Activity getActivity() {
            return WebCommonActivity.this;
        }
        
        /***
         * 分享内容
         * @param jsonData
         * @return
         */
        public int openAppSendShareData(String jsonData){
            Log4an.i(logTag, "getUserInfo() "+jsonData);
            if(!TextUtils.isEmpty(jsonData)){
                try {
                    JSONObject jsonObject = new JSONObject(jsonData);
                    final String shareUrl = JsonUtils.getStringFromJsonObj(jsonObject, "shareUrl");
                    final String imgUrl = JsonUtils.getStringFromJsonObj(jsonObject, "imgUrl");
                    final String shareTitle = JsonUtils.getStringFromJsonObj(jsonObject, "shareTitle");
                    final String shareContent = JsonUtils.getStringFromJsonObj(jsonObject, "shareContent");
                    Log4an.i(logTag, "shareUrl="+shareUrl+",shareTitle="+shareTitle+",shareContent="+shareContent+",imgUrl="+imgUrl);
                    if(!TextUtils.isEmpty(shareUrl)){
                        runOnUiThread(new Runnable() {
                            public void run() {
                                ShareModel mShare=new ShareModel(WebCommonActivity.this);
                                mShare.share(shareContent+shareUrl, shareTitle, shareUrl, imgUrl, null);
                            }
                        });
                        return JSACTION_RETURN_SUCCESS;
                    }else{
                        ToastUtil.showMessage("链接为空");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else{
                ToastUtil.showMessage("参数空异常");
            }
            return JSACTION_RETURN_FAIL;
        }

        @Override
        public void loadError(String jsonData) {
            onLoadingError();
        }
    }
    
    /**
     * 打开二级网页
     * @param title 二级网页的标题
     * @param url   要打开的网页地址
     */
    public static void openWebCommon(Activity activity, String pageTitle, String targetUrl){
        Intent intent = new Intent(activity, WebCommonActivity.class);
        intent.putExtra(INTENT_EXTRANAME_TITLE, pageTitle);
        intent.putExtra(INTENT_EXTRANAME_URL, targetUrl);
        ActivityManager.getInstance().startNextActivity(intent, activity);
    }
    /**
     * 打开二级网页,防止三层循环
     * @param title 二级网页的标题
     * @param url   要打开的网页地址
     */
    public static void openWebCommonForAvoidCycle(Activity activity, String pageTitle, String targetUrl){
        Intent intent = new Intent(activity, WebCommonActivity.class);
        intent.putExtra(INTENT_EXTRANAME_TITLE, pageTitle);
        intent.putExtra(INTENT_EXTRANAME_URL, targetUrl);
        ActivityManager.getInstance().startActivity(intent, activity);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.retry:
                doRetry();
                break;     
            default:
                break;
        }
           
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if("open".equals(getIntent().getStringExtra("push_action"))){
                    MainActivityGroup.showFromBookShelf(this, 1, true);
                    ActivityManager.getInstance().finishActivity(this);
                }
                if (webView != null && webView.canGoBack()) {
                    webView.goBack();
                    return true;
                }else{
                    ActivityManager.getInstance().finishActivity(this);
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        if(webView!=null){
            webView.stopLoading();
        }
        super.onStop();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==ShuqiWebJsBaseInterface.JUMPLOGIN_REQUESTCODE && resultCode == Activity.RESULT_OK){
            if(webView!=null){
                webView.loadUrl(currentUrl);
            }
        }else{
            ActivityManager.getInstance().finishActivity(this);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
